package com.sztz.config;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Servlet;
import java.io.IOException;

/**
 * 添加一下自动配置类，自动去掉参数里的前后空格
 * @author yzy
 * @date 2024/4/22 11:53
 */
@Configuration
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
public class AutoTrimStringConfiguration {
    /**
     * GET请求或FORM表单走这个
     * @author yzy
     * @date 2024/4/22 11:40
     */
    @ControllerAdvice
    public static class ControllerStringParamTrimConfig {
        @InitBinder
        public void initBinder(WebDataBinder binder) {
            //去除两端空格后 空串是否转换为 null   true：null   false：""
            StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
            //为 String 类对象注册编辑器
            binder.registerCustomEditor(String.class, stringTrimmerEditor);
        }
    }
    /**
     * SpringMVC是使用Jackson对参数进行反序列化,POST请求走这里
     * @author yzy
     * @date 2024/4/22 11:40
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
                .deserializerByType(String.class, new StdScalarDeserializer<String>(String.class) {
                    @Override
                    public String deserialize(JsonParser jsonParser, DeserializationContext ctx)
                            throws IOException {
                        String res = StrUtil.trim(jsonParser.getValueAsString());
                        return StrUtil.isBlank(res) ? null : res;
                    }
                });
    }
}
